package com.sun.controller.ums;


import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sun.common.MsResult;
import com.sun.pojo.UmsAdmin;
import com.sun.pojo.UmsRole;
import com.sun.service.ums.IUmsAdminService;
import com.sun.utils.JWTUtils;
import com.sun.vo.PageVo;
import com.sun.vo.UmsAdminVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author 妙妙屋
 * @since 2021-12-08
 */
@RestController
@RequestMapping("/admin")
@Api(description="后台用户管理")
public class UmsAdminController {

    @Autowired
    private IUmsAdminService iUmsAdminService;

    @PostMapping("/login")
    @ApiOperation(value="后台登录接口")
    public MsResult login(@RequestBody UmsAdmin umsAdmin){
        System.out.println(umsAdmin.getUsername()+":"+umsAdmin.getPassword());
        //根据用户名去数据库查找用户信息
        QueryWrapper<UmsAdmin> qr = new QueryWrapper<>();
        qr.eq("username",umsAdmin.getUsername());
        UmsAdmin admin = iUmsAdminService.getOne(qr);

        //查找完用户信息，比较密码是否正确
        String message = "";
        if(admin == null){
            //用户名不存在
            message = "用户名不存在";
        }else if(admin.getPassword().equals(umsAdmin.getPassword())){
            //登录成功
            Map map = new HashMap<>();
            map.put("username",admin.getUsername());
            String token = JWTUtils.generateToken(map);

            Map m = new HashMap();
            m.put("tokenHead","Miao ");
            m.put("token",token);
            return MsResult.isOkMData("操作成功",m);
        }else{
            message = "密码错误";
        }
        return MsResult.isFail(message);
    }


    @GetMapping("/info")
    @ApiOperation(value = "获取用户菜单列表")
    public MsResult info(@RequestHeader(name = "Authorization") String Authorization){
        DecodedJWT tokenInfo = JWTUtils.getTokenInfo(Authorization.substring(5));
        Map<String, Claim> claims = tokenInfo.getClaims();
        Claim username = claims.get("username");
        String uname = username.asString();
        UmsAdmin umsAdmin = iUmsAdminService.queryUmsAdminInfo(uname);
        UmsAdminVo vo = UmsAdminVo.createInstance(umsAdmin);
        return MsResult.isOkMData("操作成功",vo);
    }

    @PostMapping("/logout")
    @ApiOperation(value = "后台用户退出登录")
    public MsResult logout(){
        return MsResult.isOkMessage("退出成功");
    }

    @GetMapping("/list")
    @ApiOperation(value = "用户搜索分页展示")
    public MsResult list(String keyword,String pageNum,String pageSize){
        IPage<UmsAdmin> data = iUmsAdminService.selectPageAdmin(keyword,pageNum,pageSize);

        PageVo pageVo = PageVo.pageToVo(data);
        return MsResult.isOkData(pageVo);
    }

    @PostMapping("/register")
    public MsResult register(@RequestBody UmsAdmin umsAdmin){

            //设置创建时间
        umsAdmin.setCreateTime(LocalDateTime.now());
        umsAdmin.setLoginTime(LocalDateTime.now());
        umsAdmin.setStatus(1);

        boolean rs = iUmsAdminService.save(umsAdmin);
        if(rs){
            return MsResult.isOkData(umsAdmin);
        }
        return MsResult.isFail("注册失败，呵呵");
    }

    @ApiOperation(value = "修改账号状态")
    @PostMapping("/updateStatus/{id}")
    public MsResult updataStatus(UmsAdmin umsAdmin){
        boolean ok = iUmsAdminService.updateById(umsAdmin);
        if(ok){
            return MsResult.isOkMessage("状态修改成功");
        }
        return MsResult.isOkMessage("修改失败，稍后重试");
    }

    @ApiOperation(value = "用户删除")
    @PostMapping("/delete/{id}")
    public MsResult delete(@PathVariable Long id){
        boolean ok = iUmsAdminService.removeById(id);
        if(ok){
            return MsResult.isOkMessage("删除成功");
        }
        return MsResult.isOkMessage("删除失败，稍后重试");
    }

    @GetMapping("/role/{id}")
    @ApiOperation(value = "获取指定用户的角色信息")
    public MsResult roleInfo(@PathVariable Long id){
        //根据用户查角色   两张表可以搞定  用户角色中间表(用户id),角色表
        List<UmsRole> roleList = iUmsAdminService.getRoleByAdminId(id);
        return MsResult.isOkData(roleList);
    }


    @ApiOperation(value = "分配角色")
    @PostMapping("/role/update")
    public MsResult roleUpdate(Long adminId,String roleIds){
        //事务。。
        //取消该用户的所有角色
        Integer ok = iUmsAdminService.deleteAllRoles(adminId);

        //重新给该用户添加角色
        Integer count = iUmsAdminService.saveBatchRoles( adminId,roleIds);

        System.out.println(adminId+":"+roleIds);
        return MsResult.isOkMessage("角色分配成功");
    }

}

